import {login} from '@/api/login'
import router,{constantRouterMap,resetRouter} from "@/router/index.js"
import {msg} from "@/utils/common.js"
import Cookies from 'js-cookie'

export function addRuter(router){
    var arr = []
    router.forEach((item)=>{
        if(item.children&&item.children.length>0){
            arr.push({
                ...item,
                component:item.first?()=>import(`@/views/basePage/layout`):()=>import(`@/views${item.path}`),
                children: addRuter(item.children)
            })
        }else{
            arr.push({
                ...item,
                component:item.first?()=>import(`@/views/basePage/layout`):()=>import(`@/views${item.path}`),
            })
        }
    })
    return arr
}

const permission = {
    namespaced:true,
    state:{
        token:'',
        menu:[{name:99}],
        background:''
    },
    mutations:{
        SET_MENU(state,data){
            state.menu = data
        },
        SET_BG(state){
            const b = window.localStorage.getItem('bg')||'http://www.ranjun.xyz/img/Bg/08.jpg'
            state.background=b
        }
    },
    actions:{
        login({commit},data){
            login(data).then(res=>{
                commit("SET_MENU",res.data.menu)
                Cookies.set('token',res.data.token)
                window.sessionStorage.setItem('menu',JSON.stringify(res.data.menu))
                const routes = addRuter(res.data.menu)
                router.addRoutes(addRuter(res.data.menu),{
                    path:'*',
                    name:'404',
                    component:()=>import('@/views/basePage/404')
                })
                msg({
                    type:"success",
                    message:'登录成功'
                })
                router.push(routes[0].children[0].path)
            })
        },
        dynamicRoute({commit},data){
            return new Promise((resolve)=>{
                login(data).then(res=>{
                    resetRouter()
                    commit("SET_MENU",res.data.menu)
                    // window.sessionStorage.setItem('menu',JSON.stringify(res.data.menu))
                    router.addRoutes([...addRuter(res.data.menu),...constantRouterMap,{
                        path:'*',
                        name:'404',
                        component:()=>import('@/views/basePage/404')
                    }])
                    // return new Promise.resolve(res)
                    resolve(res)
                })
            })

        }
    }
}
export default permission